package com.appspot.web2stanza;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.*;
import javax.servlet.http.*;

public class DownloadServlet extends HttpServlet {

  public void init() {
  }

	public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {

    // get parameters
    String id = req.getParameter("id");
    String length = req.getParameter("length");

    // setup Web2Stanza
    Web2Stanza w2s = new Web2Stanza(id);

    // download
    OutputStream os = null;
    try {
      res.setContentType("application/epub+zip");
      res.setHeader("Content-Disposition", "filename=\"" + id + ".epub\"");
      res.setContentLength(Integer.parseInt(length));
      os = res.getOutputStream();
      w2s.download(os);
    } catch (Exception e) {
      throw new IOException(e);
    } finally {
      if (os != null) {
        os.close();
      }
    }
  }

  public void destroy() {
  }

}

